<?php
/**
 * News item model
 *
 * PHP version 5
 *
 * @category   Web
 * @package    Data2People
 * @subpackage Models
 * @author     Mike Bevz <mike.bevz@data2people>
 * @copyright  2007-2008 (c) Mike Bevz
 * @license    The BSD License http://data2people.com/license.txt
 * @version    SVN: $Id: News.php 14 2008-12-01 23:02:54Z michael.bevz $
 *
 */
/**
 * Includes
 */
require_once 'BaseClasses/BaseNews.php';


/**
 * News item model class
 *
 * PHP version 5
 *
 * @category   Web
 * @package    Data2People
 * @subpackage Models
 * @author     Mike Bevz <mike.bevz@data2people>
 * @copyright  2007-2008 (c) Mike Bevz
 * @license    The BSD License http://data2people.com/license.txt
 * @version    SVN: $Id: News.php 14 2008-12-01 23:02:54Z michael.bevz $
 *
 */
class News extends BaseNews
{
    /**
     * Instance of Doctrine_Pager
     *
     * @var Doctrine_Pager
     */
    private $_pager;
        
    /**
     * Initialize _pager
     *
     * @return void
     */
    private function initPager()
    {
        $this->_pager = new Doctrine_Pager(Doctrine_Query::create()
                                                        ->from('News n')
                                                        ->orderby('id DESC'), 1);
        /** @todo Define constant for maxPerPage read from UserProfile */
        $this->_pager->setMaxPerPage(1); //  Number of results per page.

    }
    
    /**
     * Temporary function to get the location name
     *
     * @param int $id Location identifier
     * @return array or string
     */
    public static function getLocations($id = 0){
        $locations = array(1    =>  'TourStart &lt;Denmark&gt;',
                           2    =>  'TourStart International');
        return ($id == 0 ? $locations : $locations[$id]);
    }

    /**
     * Return news found by keyword and location
     *
     * @param array $keywords
     * @param int $location
     *
     * @return Doctrine_Collection
     */
    public function searchNews($keywords, $location = 0, $page = 1 ) {
        $ret = array ();
        if (!is_array($keywords) || empty($keywords)){
            return $ret;
        }
        $where = '';
        foreach ($keywords as $text) {
            $where .= "n.subject LIKE '%" . (string) addslashes($text) . "%' OR ";
            $where .= "n.full_text LIKE '%" . (string) addslashes($text) . "%' OR ";
            $where .= "n.Tag.name LIKE '%" . (string) addslashes($text) . "%' OR ";
        }
        $where = ' (' . substr($where, 0, -4) . ') ';
        $this->_pager = new Doctrine_Pager(
                                Doctrine_Query :: create()
                                ->from('NewsSubject n')
                                ->where($where)
                                ->addWhere("n.News.location = $location"),
                                $page
                           );
        $this->_pager->setMaxPerPage(5);
        $res = $this->_pager->execute();
        return $res;
    }

    /**
     * Returns page
     *
     * @param integer $page Page number
     *
     * @return Doctrine_Collection
     */
    public function getPage($page)
    {
        !empty($this->_pager) or $this->initPager();
        $this->_pager->setPage((int)$page);
        return $this->_pager->execute();
    }
    
    /**
     * Returns number of pages
     *
     * @return int
     */
    public function countPage()
    {
        !empty($this->_pager) or $this->initPager();
        return $this->_pager->getLastPage();
    }
    
    /**
     * Returns current page
     *
     * @return int
     */
    public function currentPage()
    {
        !empty($this->_pager) or $this->initPager();
        return ($this->countPage() > $this->_pager->getPage())
                ? $this->_pager->getPage()
                : $this->countPage();
    }

    /**
     * Returns number of first record on the page
     *
     * @return int
     */
    public function firstRecordOnPage()
    {
        !empty($this->_pager) or $this->initPager();
        return $this->_pager->getFirstIndice();
    }
    
    /**
     * Returns number of last record on the page
     *
     * @return int
     */
    public function lastRecordOnPage()
    {
        !empty($this->_pager) or $this->initPager();
        return $this->_pager->getLastIndice();
    }
    
    /**
     * Returns number of records
     *
     * @return int
     */
    public function countOfRecords()
    {
        !empty($this->_pager) or $this->initPager();
        return $this->_pager->getNumResults();
    }
    
    /**
     * Returns true if pagination needed, false if not
     *
     * @return bool
     */
    public function needPagination()
    {
        !empty($this->_pager) or $this->initPager();
        return $this->_pager->haveToPaginate();
    }
    
    /**
     * Returns all news records
     *
     * @return Doctrine_Collection
     */
    public static function getAllNews()
    {
        $list = Doctrine_Query::create()->from('News n');
        return $list->execute();
    }

    /**
     * Returns last limited count of news records
     *
     * @param int $limit
     * @return Doctrine_Collection
     */
    public static function getLastNews($limit)
    {
        $list = Doctrine_Query::create()
                              ->from('News n')
                              ->limit($limit)
                              ->orderby('id DESC');
        return $list->execute();
    }
    
    /**
     * Returns latest news record by news number
     *
     * @return unknown
     */
    public static function getLastNewsIssue()
    {
        $q = new Doctrine_Query();
        $lastIssue = $q->select('MAX(issue_number) as issue_number')
                       ->from('News')
                       ->execute();
        return $lastIssue;
    }

    /**
     * Returns News by its id
     *
     * @param integer $id News id
     *
     * @return mixed Doctrine_Collection, array, Doctrine_Record or false if no result
     */
    public static function getNewsById($id) {
        $news = Doctrine :: getTable('News');
        return $news->find($id);
    }
        
    public static function getNewsObject($id)
    {
        if (!is_int($id)) {
            throw new TS_Model_Exception(__METHOD__ .
                      ': the method requires int as argument, got ' .
                      gettype($id));
        }
        $news = Doctrine_Query::create()->from('News')
                                        ->addWhere('id =?', array($id))
                                        ->execute();
        if (count($news) == 0) {
            return false;
        } elseif (count($news) == 1) {
            return $news->get(0);
        } else {
            return false;
        }
    }
    
    /**
     * Getting list of the existing object comments
     *
     * @param int $page
     * @param int $maxPerPage
     *
     * @return Comments
     */
    public function getComments($maxPerPage = 5)
    {
        $comments = $this->Comments->get(0);
        $comments->initNewsComments($maxPerPage);
        return $comments;
    }
    
    public function getNewsByLink($link)
    {
        if (!is_string($link)) {
            throw new TV_Model_Exception(__METHOD__ .
                      ': the method requires string as argument, got ' .
                      gettype($id));
        }
        $news = Doctrine_Query::create()->from('News n')
                                        ->addWhere('n.link =?', array($link))
                                        ->execute();
        return $news;
    }
    
    /**
     * Adds word to news item
     *
     * @param string $wordString Word to add
     *
     * @return void
     */
    public function addWord($wordString) {
        /**
         * @todo unify words
         */
        $word  = new Word();
        $words = $word->getWordByWord($wordString);
        if (count($words)>0) {
            $this->Word[] = $words[0];
        } else {
            $word       = new Word();
            $word->word = $wordString;
            $word->save();
            $this->Word[] = $word;
            
        }

    }
    
    /**
     * Adds word to news item
     *
     * @param string $tagString Tag to add
     *
     * @return void
     */
    public function addTag($tagString) {
        /**
         * @todo unify words
         */
        $tag  = new Tag();
        $tags = $tag->getByContent($tagString);
        if (count($tags)>0) {
            $this->Tag[] = $tags[0];
        } else {
            $tag          = new Tag();
            $tag->content = $tagString;
            $tag->save();
            $this->Tag[] = $tag;
            
        }

    }
    
    /**
     * Adds word to news item
     *
     * @param string $phraseString Phrase to add
     *
     * @return void
     */
    public function addPhrase($phraseString) {
        /**
         * @todo unify phrases
         */
        try {
            $this->save();
        } catch (Doctrine_Exception $e) {
            return;
        }
        $phrase  = new Phrase();
        $phrases = $phrase->getByContent($phraseString);
        if (count($phrases)>0) {
            $this->Phrase[] = $phrases[0];
        } else {
            $phrase          = new Phrase();
            $phrase->content = $phraseString;
            $phrase->length  = count(explode(" ", $phraseString));
            $phrase->save();
            $this->Phrase[] = $phrase;
            
        }

    }
    
    private function _addWordToExistingNews($wordName, $wordId)
    {
       
        /**
         * @see http://www.phpdoctrine.org/documentation/manual/
         * 0_11?one-page#working-with-objects:many-to-many-relations
         * :creating-a-new-link
         */
        $wordRef = new WordRefNews();
        $wordRef->word_id = $word_id;
        $wordRef->news_id = $this->id;
        $wordRef->save();
    }
    private function _addWordToNewNews($tagName, $wordId)
    {
        $this->state('TDIRTY');
        $this->save();
        //$tag = new Word();
        //$tag_id = $tag->add($tagName);
        $wordRef = new WordRefNews();
        $wordRef->word_id = $word_id;
        $wordRef->news_id = $this->id;
        $wordRef->save();
    }
}